//导入express
var express = require('express');
var router = express.Router();
//导入配置文件
const {secret} = require('../config/config')
//导入模型文档           用户的模型文档
const CourseModel = require('../models/CourseModel');
const UserModel = require('../models/UserModel');
const TakeorderModel = require('../models/TakeorderModel')
const orderModel = require('../models/orderModel')
const md5 = require('md5');
//导入中间件(验证token的中间件)
let checkTokenMiddleware = require('../middlewares/checkTokenMiddleware');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//获取全部课程列表       checkTokenMiddleware（验证token的中间件函数）如果丢失验证失败就不应该请求成功
router.get('/allcourse',(req,res)=>{
  CourseModel.find()
  .then(data =>{
    res.json({
      statuscode:"000",
      code: '3000',
      msg: '查询全部课程成功',
      data: data
    })
  })
  .catch(err =>{
    console.log("查询全部课程失败")
    throw err
  })
})


//查询单个课程
router.post('/onecourse',(req,res)=>{
  let{coursetitle} = req.body
  CourseModel.find({coursetitle})
  .then(data =>{
    res.json({
      statuscode:"000",
      code: '3000',
      msg: '查询该门课程成功',
      data: data
    })
  })
  .catch(err =>{
    console.log("查询该课程失败")
    throw err
  })
})

//购买课程
router.post('/surebuycourse',checkTokenMiddleware,(req,res)=>{
  let {coursetitle,username} = req.body
  // 假设要添加的帖子对象
  const newcourse = {
    coursetitle: coursetitle
  };
  UserModel.updateOne({username:username},{$push:{"courseorder":newcourse}})
  .then(data=>{
    res.json({
      statuscode:"000",
      code:"3001",
      msg:"用户购买课程成功", 
      data:data
    })
  })
  .catch(err =>{
    throw err
  })
})

//查询用户购买的课程
router.post('/myclass', checkTokenMiddleware, (req, res) => {
  let { username } = req.body;
  UserModel.findOne({ username: username })
    .then(data => {
      let courseTitles = data.courseorder.map(item => item.coursetitle);
      CourseModel.find({ coursetitle: { $in: courseTitles } })
        .then(data => { 
          res.json({
            courseorder: data,
            statuscode: "000",
            msg: "查询已购课程成功"
          });
        })
        .catch(err => {
          throw err;
        });
    })
    .catch(err => {
      throw err;
    });
});

//获取全部接单数据
router.get('/alltakeorder',(req,res)=>{
  TakeorderModel.find()
  .then(data =>{
    res.json({
      statuscode:"000",
      msg:"查询全部的接单数据成功",
      data:data
    })
  })
  .catch(err =>{
    console.log("查询全部的接单数据失败")
  })
})

//购买订单
router.post('/surebuyservice',checkTokenMiddleware,(req,res)=>{
  let {servicetitle,username,type,price,buytime,booktime,uuid} = req.body

  UserModel.findOne({ username:username })
  .then(data => {
    if (data) {
      // 在找到的特定用户中进行操作，添加新对象到数组中
      const newItem = { 
        username:username,
        servicetitle:servicetitle,
        buytime:buytime, 
        type:type, 
        price:price,
        booktime:booktime,
        uuid:uuid
      };
      data.allorder.push(newItem);

      res.json({
        statuscode:'000',
        msg:'用户购买服务成功'
      })
      // 保存更新后的用户
      return data.save();
    } else {
      throw new Error("未找到特定用户");
    }
  })
  .catch(err => {
    console.log("错误发生", err);
  });
})

//删除订单/取消订单
router.post('/surecancel',checkTokenMiddleware,(req,res)=>{
  let {username} = req.user
  let {uuid} =req.body
  UserModel.findOneAndUpdate({username:username},
    { $pull: { allorder: { uuid: uuid } } }, 
    { new: true })
  .then(data =>{
    res.json({
      statuscode:"000",
      msg:"取消/删除订单成功",
      data:data
    })
  })
  .catch(err =>{
    throw err
  })
})


//提交定制服务
router.post('/customize',checkTokenMiddleware,(req,res)=>{
  let{phonenumber,value,select,uuid} = req.body
  let {username} = req.user
  
  UserModel.findOne({username:username})
  .then(data =>{
    if(data){
      const newItem = { 
        type:"定制服务",
        phonenumber:phonenumber,
        value:value, 
        select:select,
        uuid:uuid
      };
      
      data.allorder.push(newItem)
  
      res.json({
        statuscode:'000',
        msg:'发送定制服务成功',
        data:data
      })
      // 保存更新后的用户
      return data.save();
    }else{
      throw new Error("未找到特定用户");
    }
  })
  .catch(err =>{
    throw err
  })
})


//提交申请
router.post('/application',checkTokenMiddleware,(req,res)=>{
  let {username} = req.user
  let {jobtitle,jobrequest,jobsalary,jobplace,uuid} = req.body
  UserModel.findOne({username:username})
  
  .then(data =>{
    if(data){
      let newitem = {
        uuid,
        jobtitle:jobtitle,
        jobrequest:jobrequest,
        jobsalary:jobsalary,
        jobplace:jobplace
      }

      data.application.push(newitem)

      res.json({
      statuscode:"000",
      msg:"提交申请成功",
      data:data
      })

    // 保存更新后的用户
    return data.save();
    }else{
      throw new Error("未找到特定用户");
    }
  })
  .catch(err =>{
    throw err
  })
})

//取消申请
router.delete('/cancelapplication',checkTokenMiddleware,(req,res)=>{
  let {username} = req.user
  let {uuid} = req.body

  UserModel.findOneAndUpdate({username:username},
    { $pull: { application: { uuid: uuid } } })
    .then(data =>{
      res.json({
        statuscode:"000",
        msg:"取消申请成功",
        data:data
      })
    })
    .catch(err =>{
      throw err
    })
})


//获取订单数据（呈现在购买下单界面的）
router.get('/orderdata',(req,res)=>{
  orderModel.find()
  .then(data =>{
    res.json({
      statuscode:"000",
      msg:"已获取数据",
      data:data
    })
  })
  .catch(err =>{
    throw err
  })
})

module.exports = router;
